package com.heba.greenmulu.diary;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.facebook.common.Common;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.heba.Cfg;
import com.heba.adapter.FmPagerAdapter;
import com.heba.bean.ItemShareObject;
import com.heba.bean.PhotoObject;
import com.heba.bean.ShareObject;
import com.heba.bean.user.UserObject;
import com.heba.config.CommonConfig;
import com.heba.fragment.mine.MineSelectFriendsFragment;
import com.heba.fragment.mine.MineSelectPhotoFragment;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.ItemReportActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.ZoomPhotoActivity;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.greenmulu.message.ItemMessageChatDetailActivity;
import com.heba.greenmulu.message.ItemMessageSendActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.popupwindow.SharePopupWindow;
import com.heba.popupwindow.callback.ShareListener;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.utils.IndicatorLineUtil;
import com.heba.utils.ToastShow;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 用戶個人主頁
 * Created by jason on 2020/1/21.
 */
public class ItemPersonHomePageActivity extends BaseActivity {

    /**
     * topbar
     */
    private View view_background;
    private ImageView img_back;
    private ImageView img_more;
    private TextView txt_title;

    /**
     * account view
     */
    private ImageView img_avatar;
    private ImageView img_copy_link;
    private ImageView img_message;
    private TextView txt_focus;
    private TextView txt_nickname;
    private TextView txt_desc;
    private LinearLayout linearLayout;
    private AppBarLayout appBarLayout;
    private float avatarTop;
    private float minTop = 15;
    private float bannarHeight ;
    private ImageView bannar_image;
    private int selectIndex = 0;
    private ConstraintLayout bottomLine1;
    /**
     * 分享彈出框
     */
    private SharePopupWindow sharePopupWindow;
    private ShareObject shareObject;

    /**
     * tablayout
     */
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FmPagerAdapter pagerAdapter;

    /**
     * fragment
     */
    private MineSelectPhotoFragment mineSelectPhotoFragment;
    private MineSelectFriendsFragment mineSelectFriendsFragment;
    private ArrayList<Fragment> fragments = new ArrayList<>();

    private UserObject userObject;

    /**
     * 需要獲取的用戶的UserID
     */
    private String buddyUserID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_person_homgpage);
        findViewById();
        initView();
        initPopupWindow();
        initFragments();
        setCustomTabView();
        getPersonInfoData();
    }

    @Override
    protected void findViewById() {
        view_background = findViewById(R.id.view_background);
        img_back = findViewById(R.id.img_diary_write);
        img_more = findViewById(R.id.img_setting);
        txt_title = findViewById(R.id.txt_mine_title);
        img_avatar = findViewById(R.id.img_avatar);
        img_copy_link = findViewById(R.id.img_copy_link);
        img_message = findViewById(R.id.img_message);
        txt_focus = findViewById(R.id.txt_edit_account);
        txt_nickname = findViewById(R.id.txt_nickname);
        txt_desc = findViewById(R.id.txt_desc);
        tabLayout = findViewById(R.id.tabLayout);
        bottomLine1 = findViewById(R.id.bottom_line_1);
        viewPager = findViewById(R.id.viewPager);
        bannar_image = findViewById(R.id.bannar_image);
        linearLayout = findViewById(R.id.linear_top);
        appBarLayout = findViewById(R.id.appbar);
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density1 = dm.density;
        float width3 = dm.widthPixels;
        bannarHeight = width3/16*9;
    }

    @Override
    protected void initView() {
        shareObject = new ShareObject();
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            buddyUserID = bundle.getString(CommonConfig.SEND_USER_ID, "");
        }

        img_back.setImageResource(R.drawable.icon_back_white);
        img_more.setImageResource(R.drawable.icon_more_white_point);

        img_back.setOnClickListener(v -> finishActivity());

        img_more.setOnClickListener(v -> {
            if (null == userObject)
                return;
            shareObject.setShareTitle(String.format(this.getResources().getString(R.string.share_account_title), userObject.getAccount()));
            shareObject.setShareContent(String.format(this.getResources().getString(R.string.share_account_content), userObject.getAccount()));
            shareObject.setShareImageUrl(userObject.getIcon());
            shareObject.setShareLink(userObject.getLink());
            sharePopupWindow.setShareObject(shareObject);
            view_background.setVisibility(View.VISIBLE);
            sharePopupWindow.showAtLocation(img_more, Gravity.BOTTOM, 0, 0);
        });
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                getTop();
                float height = DensityUtils.dip2px(getBaseContext(),bannarHeight);
                float top = avatarTop;
                if (top <=295){
                }
//                bannar_image.setAlpha((avatarTop-140)/(DensityUtils.dip2px(getBaseContext(),bannarHeight)/2-200));

            }
        });
        img_more.setVisibility(View.INVISIBLE);
        txt_focus.setVisibility(View.INVISIBLE);
        img_copy_link.setVisibility(View.INVISIBLE);
        img_message.setVisibility(View.INVISIBLE);
    }
    private void getTop(){
        int[] viewLocation = new int[2];
        img_avatar.getLocationInWindow(viewLocation);
        avatarTop = viewLocation[1];
    }
    /**
     * 分享彈出框
     */
    private void initPopupWindow() {
        List<ItemShareObject> shareList1 = new ArrayList<>();
        List<ItemShareObject> shareList2 = new ArrayList<>();

        /**
         * 分享至社交軟件
         */
        int[] ids = {R.drawable.icon_more_share_facebook, R.drawable.icon_more_share_whatsapp, R.drawable.icon_more_share_wechat, R.drawable.icon_more_share_friends};
        String[] contents = getResources().getStringArray(R.array.share_contents_normal);
        int[] shareTypes = {CommonConfig.SHARE_TO_FACEBOOK, CommonConfig.SHARE_TO_WHATSAPP, CommonConfig.SHARE_TO_WECHAT, CommonConfig.SHARE_TO_CIRCLE};
        for (int i = 0; i < ids.length; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids[i]);
            shareObject.setShareContent(contents[i]);
            shareObject.setShareType(shareTypes[i]);
            shareList1.add(shareObject);
        }

        /**
         * 本地分享
         */
        int[] ids1 = {R.drawable.icon_more_send, R.drawable.icon_more_report,R.drawable.icon_fengsuo1};
        String[] contents1 = getResources().getStringArray(R.array.share_contents_person);
        int[] shareTypes1 = {CommonConfig.SHARE_TO_SEND_USER, CommonConfig.SHARE_TO_REPORT_USER,CommonConfig.BLOCK_USER};

        if (buddyUserID.equals("3337")){
            ids1 = new int[]{R.drawable.icon_more_send, R.drawable.icon_more_report};
            contents1 = getResources().getStringArray(R.array.share_contents_person_no_block);
            shareTypes1 = new int[]{CommonConfig.SHARE_TO_SEND_USER, CommonConfig.SHARE_TO_REPORT_USER};
        }
        for (int i = 0; i < ids1.length; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids1[i]);
            shareObject.setShareContent(contents1[i]);
            shareObject.setShareType(shareTypes1[i]);
            shareList2.add(shareObject);
        }

        sharePopupWindow = new SharePopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        sharePopupWindow.setShareList(shareList1, shareList2);

        /**
         * 分享接口实现
         */
        sharePopupWindow.setOnShareListener(new ShareListener(ItemPersonHomePageActivity.this) {
            @Override
            public void sendUser() {
                Bundle bundle = new Bundle();
                bundle.putInt(CommonConfig.TYPE, CommonConfig.TYPE_SEND_USER);
                bundle.putString(CommonConfig.MESSAGE_ID, buddyUserID);
                openActivity(ItemMessageSendActivity.class, bundle);
            }

            @Override
            public void reportUser() {
                Bundle bundle = new Bundle();
                bundle.putInt(CommonConfig.TYPE, 1);
                bundle.putString(CommonConfig.REPORT_ID, buddyUserID);
                openActivity(ItemReportActivity.class, bundle);
            }

            @Override
            public void blockUser() {
                blockBusinessUser();
            }
        });

        sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });
    }

    /**
     * initFragments
     */
    private void initFragments() {
        mineSelectPhotoFragment = MineSelectPhotoFragment.newInstance(buddyUserID);
        mineSelectFriendsFragment = MineSelectFriendsFragment.newInstance(buddyUserID);
        fragments.add(mineSelectPhotoFragment);
        fragments.add(mineSelectFriendsFragment);
    }

    /**
     * 设置自定义tab
     */
    private void setCustomTabView() {
        /**
         * 添加tab
         */
        for (int i = 0; i < 2; i++) {
            tabLayout.addTab(tabLayout.newTab());
        }

        /**
         * 关联viewpager,设置adapter
         */
        tabLayout.setupWithViewPager(viewPager, false);
        pagerAdapter = new FmPagerAdapter(fragments, getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(3);

        /**
         * 设置tab文字,必须在关联viewpager之后设置，否则文字不显示
         */
        Objects.requireNonNull(tabLayout.getTabAt(0)).setCustomView(getTabItemView(R.drawable.image_post_selector));
        Objects.requireNonNull(tabLayout.getTabAt(1)).setCustomView(getTabItemView(R.drawable.image_friends_selector));

        /**
         * 设置指示线长度间隔(单位dp)
         */
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                IndicatorLineUtil.setIndicator(tabLayout, 0, 0);
            }
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tabLayout.getSelectedTabPosition();
                Resources resources = getResources();
                DisplayMetrics dm = resources.getDisplayMetrics();
                int width3 = dm.widthPixels;
                TranslateAnimation translateAnimation1 = new TranslateAnimation(selectIndex*(width3/2),position*(width3/2),0,0);
                translateAnimation1.setDuration(300);
                translateAnimation1.setFillEnabled(true);//使其可以填充效果从而不回到原地
                translateAnimation1.setFillAfter(true);//不回到起始位置
                bottomLine1.startAnimation(translateAnimation1);


                translateAnimation1.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        selectIndex = tabLayout.getSelectedTabPosition();



                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 获取itemview
     *
     * @param icon
     * @return
     */
    private View getTabItemView(int icon) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_tab_layout, null);
        ImageView iv_icon = view.findViewById(R.id.iv_icon);
        iv_icon.setImageResource(icon);
        return view;
    }

    /**
     * 更新用戶信息View
     */
    @SuppressLint("ResourceType")
    private void updatePersonInfoView(UserObject object) {
        mineSelectPhotoFragment.setPostCount(Integer.parseInt(object.getDiaryCount()));
        mineSelectPhotoFragment.setTaggedCount(object.getPasteCount());
        mineSelectFriendsFragment.setFollowingCount(object.getTrackCount());
        mineSelectFriendsFragment.setFollowerCount(object.getFanCount());
        txt_title.setText(object.getAccount());
        txt_nickname.setText(object.getNickname());
        txt_desc.setText(CommonUtils.getDecodeText(object.getProfile()));
        GlideUtil.loadImageWithPlaceHolderID(this, object.getIcon(), img_avatar, R.drawable.icon_head_portrait);

        txt_focus.setVisibility(View.VISIBLE);
        img_message.setVisibility(View.VISIBLE);
        img_copy_link.setVisibility(userObject.getWebside().isEmpty() ? View.INVISIBLE : View.VISIBLE);
        img_more.setVisibility(View.VISIBLE);

        txt_focus.setBackground(getDrawable(R.drawable.button_mine_follow_selector1));
        txt_focus.setTextColor(this.getResources().getColorStateList(R.drawable.text_mine_follow_selector1, null));
        //判斷顯示關注按鈕
        switch (Integer.valueOf(object.getStatus())) {
            case 0:
                //表示该用户是自己本人
                txt_focus.setVisibility(View.INVISIBLE);
                img_message.setVisibility(View.INVISIBLE);
                img_copy_link.setVisibility(View.INVISIBLE);
                img_more.setVisibility(View.INVISIBLE);
                break;
            case 1:
                //已关注
                txt_focus.setCompoundDrawables(null, null, null, null);
                txt_focus.setText(getResources().getString(R.string.mine_focus2));
                txt_focus.setSelected(true);
                break;
            case 2:
                //未关注
                Drawable left = getResources().getDrawable(R.drawable.icon_diary_focus_on, null);
                left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
                txt_focus.setCompoundDrawablePadding(DensityUtils.dip2px(this, 4));
                txt_focus.setCompoundDrawables(left, null, null, null);
                txt_focus.setText(getResources().getString(R.string.mine_focus));
                txt_focus.setSelected(false);
                break;
            default:
                txt_focus.setVisibility(View.INVISIBLE);
                img_copy_link.setVisibility(View.INVISIBLE);
                img_more.setVisibility(View.INVISIBLE);
                break;
        }

        /**
         * 复制网站地址
         */
        img_copy_link.setOnClickListener(v -> {
            if (!userObject.getWebside().isEmpty()) {
                ToastShow.displayToast(ItemPersonHomePageActivity.this, getResources().getString(R.string.mine_copy_link));
                CommonUtils.copyText2Clipboard(ItemPersonHomePageActivity.this, userObject.getWebside());
            }
        });

        /**
         * 关注用户
         */
        txt_focus.setOnClickListener(v -> {
            if (object.getUserID().equals("3337")){
                return;
            }
            if (object.getStatus().equals("2")) {
                //未关注用户时的点击处理
                loading.Start();
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        loading.End();
                        getPersonInfoData();
                    }

                    @Override
                    public void Fail(String error) {
                        loading.End();
                    }
                }).followUser(this, buddyUserID);
            } else {
                //已关注用户时的点击处理
                loading.Start();
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        loading.End();
                        getPersonInfoData();
                    }

                    @Override
                    public void Fail(String error) {
                        loading.End();
                    }
                }).unFollowUser(this, buddyUserID);
            }
        });

        /**
         * 查看頭像大圖
         */
        img_avatar.setOnClickListener(v -> {
            List<PhotoObject> list = new ArrayList<>();
            PhotoObject photoObject = new PhotoObject();
            photoObject.setImageUrl(object.getIcon());
            list.add(photoObject);
            Bundle bundle = new Bundle();
            bundle.putInt(CommonConfig.TYPE, 1);
            bundle.putSerializable(CommonConfig.PHOTOLIST, (Serializable) list);
            openActivityWithFadeInAnimation(ZoomPhotoActivity.class, bundle);
        });

        /**
         * 私信
         */
        img_message.setOnClickListener(v -> {
            Bundle bundle1 = new Bundle();
            bundle1.putString(CommonConfig.USER_NAME, object.getAccount());
            bundle1.putString(CommonConfig.USER_ICON, object.getIcon());
            bundle1.putString(CommonConfig.SEND_USER_ID, object.getUserID());
            bundle1.putInt(CommonConfig.ACCOUNT_TYPE,object.getAccountType());
            openActivity(ItemMessageChatDetailActivity.class, bundle1);
        });

    }
    private void blockBusinessUser(){
        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {
                progressDialog.dismiss();

                ToastShow.displayToast(ItemPersonHomePageActivity.this,getBaseContext().getResources().getString(R.string.had_bloack));
                finishActivity();
            }

            @Override
            public void Fail(String error) {
                progressDialog.dismiss();
                if (error.equals("")){
                    ToastShow.displayToast(ItemPersonHomePageActivity.this,getBaseContext().getResources().getString(R.string.had_bloack));
                }
            }
        }).BlockUser(ItemPersonHomePageActivity.this,buddyUserID);

    }
    /**
     * 獲取用戶個人信息數據
     */
    private void getPersonInfoData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("BuddyUserID", buddyUserID);
        client.get(Cfg.BaseUrl + "/User/GetBuddyInfo", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response.trim()).getJSONObject("Result");
                            userObject = new Gson().fromJson(jsonObject.toString(), UserObject.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 顯示用戶個人信息
                         */
                        if (null != userObject) {
                            updatePersonInfoView(userObject);
                        }
                        Resources resources = getResources();
                        DisplayMetrics dm = resources.getDisplayMetrics();
                        float density1 = dm.density;
                        int width3 = dm.widthPixels;
                        ViewGroup.LayoutParams linearParams = linearLayout.getLayoutParams();
                        if (userObject.getBannerUrl().length() <= 0 ){
                            linearParams.height = 170;
                            bannar_image.setVisibility(View.INVISIBLE);

                        }else {
                            bannar_image.setVisibility(View.VISIBLE);

                            linearParams.height = width3/16*9;

                            GlideUtil.loadImageWithDefaultPlaceHolder(getBaseContext(),userObject.getBannerUrl(),bannar_image);
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

}
